<template>
	<z-paging ref="paging" @query="queryList" :refresherEnabled="true" :loadingMoreEnabled="false"
		:auto="false" :hideEmptyView="true">
		<view slot="top">
			
		</view>
		
		<view v-show="!isShowSkeleton">
			<!-- 轮播图 -->
			<view>
				<u-swiper :list="topBannerList" height="293" @click="handleTopBanner"></u-swiper>
			</view>
			
			<!-- 客服 -->
			<view style="position: relative; top: -50rpx;">
				<view class="u-m-l-30 bg-white u-p-l-40 u-p-t-30 u-p-b-30 "
							style="position: absolute; width: 95%; border-radius: 30rpx 0rpx 0rpx 30rpx;box-shadow: 0rpx 2rpx 20rpx #E8E9EA;">
					<view class="u-font-28 text-bold">
						<text>咨询客服: </text>
						<text class="u-m-l-20">晒单加囎</text>
						<text>+优惠券</text>
						<text>+互动好礼</text>
					</view>
					<view class="u-flex u-m-t-30 text-bold">
						<view class="u-flex-1" @click="handlePoint">
							<text class="u-m-r-10">积分</text>
							<u-count-to :duration="countDuration" :startVal="0" :endVal="pointBalance" color="#000000" fontSize="14" bold decimals="0" separator=","></u-count-to>
						</view>
						<view class="u-flex-1">
							<text class="u-m-r-10">成长币</text>
							<u-count-to :duration="countDuration" :startVal="0" :endVal="cashBalance" color="#000000" fontSize="14" bold decimals="0" separator=","></u-count-to>
						</view>
						<view class="u-flex-1" @click="handleCoupon">
							<text class="u-m-r-10">优惠券</text>
							<u-count-to :duration="countDuration" :startVal="0" :endVal="availableCouponCount" color="#000000" fontSize="14" bold decimals="0" separator=","></u-count-to>
						</view>
					</view>
					<view style="position: absolute; top: -30rpx; right: 10rpx;">
						<button open-type="contact" plain hover-class="none" size="mini" style="border: 0px;">
							<image src="~@/static/images/home/service.svg" style="width: 110rpx; height: 110rpx;"></image>
						</button>
					</view>
				</view>
			</view>
			
			<view class="hot-bg u-m-l-30 u-p-l-40 u-p-r-40 u-p-t-30" style="border-radius: 30rpx 0rpx 0rpx 30rpx; margin-top: 150rpx;">
				<view class="bg-white b-r-30" style="position: relative;">
					<view class="u-flex"  @click="handleGoodsDetail(item)" v-for="(item, index) in mainSkuList" :key="index">
						<view class="u-flex-1" style="margin-bottom:-10rpx">
							<image :src="item.imageUrl" style="width: 200rpx; height: 200rpx; border-radius: 30rpx 0rpx 0rpx 30rpx; "></image>
						</view>
						<view class="u-flex-3 u-p-l-20">
							<view>
								<text class="u-font-34 text-bold">{{item.skuShortName}}</text>
							</view>
							<view >
								<text style="color: #D88715;" class="u-font-22">专利配方护航 突破成长新高度</text>
							</view>
							<view class="u-m-t-10 text-money">
								<text class="u-font-32 u-m-r-5">¥</text>
								<u-count-to :duration="countDuration" separator="," :startVal="0" :endVal="formatMoney(item.sellPrice)" color="#C16D09" fontSize="22" bold decimals="0"></u-count-to>
							</view>
						</view>
					</view>
					
					<view style="position: absolute; bottom: -50rpx;right: 20rpx;">
						<image src="~@/static/images/home/shopping_cart.svg" style="width: 90rpx; height: 90rpx;"></image>
					</view>
				</view>
				<view class="u-m-t-20">
					<text class="u-font-32 text-bold">精选商品</text>
				</view>
				<!-- 精选商品轮播 -->
				<view class="u-m-t-20" v-if="subMainList.length > 0">				
					<u-scroll-list indicatorWidth="0">
						<view v-for="(item, index) in subMainList" :key="index" class="u-m-r-20" >
							<view class="bg-white b-r-30" style="width: 200rpx;" @click="handleGoodsDetail(item)">
								<view>
									<image :src="item.imageUrl" mode="aspectFill" style="height: 200rpx;width: 200rpx; border-radius: 30rpx 30rpx 0rpx 0rpx;"></image>
								</view>
								<view class="u-text-center u-p-t-10 u-p-b-20">
									<view>{{item.skuShortName}}</view>
									<view class="text-money text-bold u-m-t-10">
										<text class="u-m-r-5 u-font-24">¥</text>
										<u-count-to :duration="countDuration" :startVal="0" :endVal="formatMoney(item.sellPrice)" separator="," color="#C16D09" fontSize="16" bold decimals="0"></u-count-to>
									</view>
								</view>
							</view>
						</view>
					</u-scroll-list>
				</view>
			</view>
			
			<view class="u-m-t-40 bg-white u-m-l-30" v-if="activityList.length > 0">
				<!-- <z-swiper v-model="activityList" :options="{slidesPerView : 'auto',centeredSlides: true,spaceBetween: 14}">
					<z-swiper-item v-for="(item,index) in activityList" :key="index" :custom-style="{width:'88%',height:'auto'}">
						<image :src="item.bannerImage" mode="aspectFill" style="height: 240rpx;width: 100%; border-radius: 30rpx;" @click="handleNavBanner(item)"></image>
					</z-swiper-item>
				</z-swiper> -->
				
				<u-swiper :list="activityBannerList"
									@click="handleNavBanner" 
									previousMargin="0" 
									nextMargin="30"
									circular
									radius="10"></u-swiper>
			</view>
			
			<view>
				<view class="u-m-40">
					<!-- <text class="u-font-32 text-bold">热门推荐</text> -->
					<u-tabs 
						:list="tabMenuList"
						lineWidth="0"
						:activeStyle="{
							color: '#C16D09',
							fontWeight: 'bold',
							fontSize:'32rpx',
							transform: 'scale(1.05)'
						}"
						:inactiveStyle="{
							color: '#404040',
							fontSize:'28rpx',
							transform: 'scale(1)'
						}"
						itemStyle="padding-left: 0rpx; padding-right: 30rpx; height: 34px;"
						:current="tabCurrentIndex"
						@change="handleTabMenuChange">
					</u-tabs>
				</view>
				<view v-show="tabCurrentIndex == 0">
					<HotGoodsSku ref="hotGoodsSkuRef" model="vertical" isShowPointMall></HotGoodsSku>
				</view>
				<view v-show="tabCurrentIndex == 1">
					<ShopEquity ref="shopEquityRef" @equityLoadCompleted="handleEquityLoadCompleted"></ShopEquity>
				</view>
			</view>
			
			<!-- <view style="margin-right: -26rpx;">
				<image src="~@/static/images/home/bottom.png" style="width: 100%;height: 670rpx;"></image>
			</view> -->
			
			<view class="u-m-t-30 u-m-l-30 u-m-b-30 bg-white u-p-66" style="border-radius: 30rpx 0rpx 0rpx 30rpx; box-shadow: 0px 5px 10px #E9EDF2;">
				<view>
					<text class="u-font-30 text-bold" style="color: #CA4343;">温馨提示 | Reminder</text>
				</view>
				<view class="u-m-t-6">
					<text class="u-font-28" style="opacity: 0.6;">近期收到部分顾客反馈，有不法份子通过非法渠道窃取顾客快递信息，并且使用第三方聊天工具或电话短信等方式，欺骗顾客进行拒签、退款、补运费等行为</text>
				</view>
				
				<view class="u-m-t-40">
					<text class="u-font-30 text-bold" style="color: #CA4343;">本店郑重声明:</text>
				</view>
				<view class="u-m-t-6">
					<text class="u-font-28" style="opacity: 0.6;">客服只通过官方平台或官方微信与顾客进行沟通，不会使用任何第三方工具。如遇到不明来源信息，请及时删除对方或通过此平台与客服进行核实，切勿相信其他渠道任何不明信息!</text>
				</view>
			</view>
			
		</view>
		
		<skeleton v-if="isShowSkeleton"></skeleton>
		
		<root-portal>
			<u-overlay :show="isShowCoupon" @click="handleCouponClick">
				<view @click.stop="handleNavUserInner">
					<image src="~@/static/images/home/popup.jpg" style="position: absolute; height: 639rpx; width: 402rpx; top: 35%;left: 23%;border-radius: 30rpx;"></image>
				</view>
			</u-overlay>
		</root-portal>
		
	</z-paging>
</template>

<script>
	import {jumpTypeEnum, BooleanEnum, couponCurrentStatusEnum, registerTypeEnum, goodsSpuTypeEnum } from '@/common/const.js'
	import {getBanner, goodsSpuList, getTopBanner} from '@/api/home.js'
	import HotGoodsSku from '@/components/hot_goods_sku/index.vue'
	import ShopEquity from '@/components/equity/index.vue'
	import {mapGetters} from 'vuex'
	import {getUserInfo} from '@/api/login.js'
	import {getAvailableCoupon} from '@/api/coupon.js'
	import {miniProgramCheckUpdate} from '@/common/util.js'
	import {skeleton} from '@/components/skeleton/home.vue'
	import {userInnerLogin} from '@/api/user.js'
	
	export default{
		data(){
			return{
				goodsSpuTypeEnum,
				registerTypeEnum,
				countDuration:200,
				BooleanEnum,
				
				goodsList:[],
				// 顶部轮播图
				topBannerList:[],
				// 活动列表
				activityList:[],
				// 活动轮播图列表
				activityBannerList:[],
				// 商品列表
				goodsSpuList:[],
				// 主推荐列表
				mainSkuList:[],
				// 二级推荐列表
				subMainList:[],
				// 可用优惠券个数
				availableCouponCount:0,
				isShowSkeleton:true,
				tabMenuList:[],
				tabCurrentIndex:0,
				isShowCoupon:false,
				hasFirstLoad:true
			}
		},
		components:{
			HotGoodsSku,
			skeleton,
			ShopEquity
		},
		computed:{
			...mapGetters(['isLogin', 'userInfo', 'invitedCode', 'userInnerIsLogin']),
			
			/**
			 * 积分余额
			 */
			pointBalance(){
				if(this.userInfo && this.userInfo.shopUserInfo){
					return this.userInfo.shopUserInfo.pointBalance
				}
				return 0
			},
			
			/**
			 * 提现余额
			 */
			cashBalance(){
				if(this.userInfo && this.userInfo.shopUserInfo){
					return this.userInfo.shopUserInfo.cashBalance
				}
				return 0
			}
		},
		onLoad() {
			this.init()
		},
		onShareAppMessage(res) {
			let invitedCode = this.userInfo.invitedCode
			let type = 'home'
			let url = `/pages/main/index?invitedCode=${invitedCode}&type=${type}&registerType=${registerTypeEnum.share_friend}`
			console.log(url)
			return {
				title: '伊利高个子母婴专卖店',
				path: url
			}
		},
		onShareTimeline(res){
			let invitedCode = this.userInfo.invitedCode
			let type = 'home'
			let url = `/pages/main/index?invitedCode=${invitedCode}&type=${type}&registerType=${registerTypeEnum.share_friend_circle}`
			console.log(url)
			return {
				title: '伊利高个子母婴专卖店',
				path: url
			}
		},
		onShow(){
			// #ifdef MP-WEIXIN
			console.log('检查更新')
			miniProgramCheckUpdate()
			// #endif
		},
		methods:{
			
			/**
			 * 初始化
			 */
			init(){
				this.reload()
				// #ifdef MP-WEIXIN
				this.shareMenuStatus()
				uni.$on("reloadShareMenuStatus",()=>{
					console.log("刷新分享状态")
					this.shareMenuStatus()
				})
				// #endif
			},
			
			/**
			 * 判断是否可以分享
			 */
			shareMenuStatus(){
				if(this.isLogin){
					console.log("打开分享")
					uni.showShareMenu({
						menus: ['shareAppMessage', 'shareTimeline']
					})
				} else {
					console.log("关闭分享")
					uni.hideShareMenu({
						
					})
				}
			},
			
			/**
			 * 重新加载
			 */
			reload(){
				setTimeout(()=>{
					// 重新加载
					this.$refs.paging.reload()
				},100)
			},
			
			async queryList(){
				this.mainSkuList = []
				this.subMainList = []
				this.activityList = []
				this.topBannerList = []
				this.activityBannerList = []
				this.tabMenuList = []
				this.tabCurrentIndex = 0
				this.isShowSkeleton = true
				this.tabMenuList.push({name: '热门推荐'})
				
				// 初始化顶部轮播图
				await this.loadTopBanner()
				// 初始化商品
				await this.loadGoodsSpuList()
				// 初始化轮播图
				await this.loadBanner()
				
				this.$nextTick(()=>{
					// 加载热销商品
					this.$refs.hotGoodsSkuRef.init()
					// 权益包
					this.$refs.shopEquityRef.init()
					
					// 第一次加载的场合
					if(this.hasFirstLoad){
						// 弹窗
						//this.isShowCoupon = true
						this.hasFirstLoad = false
					}
					
				})
				if(this.isLogin){
					// 登录的场合，重新获取用户信息
					this.$store.dispatch("updateUserInfo")
					// 加载当前用户优惠券
					await this.loadCoupon()
				}
				this.isShowSkeleton = false
				this.$refs.paging.complete([]);
			},
			
			/**
			 * 初始化顶部轮播图
			 */
			loadTopBanner(){
				return new Promise(resolve=>{
					getTopBanner().then(res=>{
						res.data.forEach(item=>{
							item.bannerImage = JSON.parse(item.bannerImage)
							if(item.bannerImage.length > 0){
								this.topBannerList.push(item.bannerImage[0].materialUrl)
							}
						})
						resolve()
					})
				})
			},
			
			/**
			 * 初始化轮播图
			 */
			loadBanner(){
				return new Promise(resolve=>{
					getBanner().then(res=>{
						this.activityList = res.data
						res.data.forEach(item=>{
							item.bannerImage = JSON.parse(item.bannerImage)
							if(item.bannerImage.length > 0){
								this.activityBannerList.push(item.bannerImage[0].materialUrl)
							}
						})
						resolve()
					})
				})
			},
			
			/**
			 * 初始化商品
			 */
			loadGoodsSpuList(){
				return new Promise(resolve=>{
					// 获取商品列表
					goodsSpuList({
						spuType: goodsSpuTypeEnum.common
					}).then(res=>{
						this.goodsSpuList = res.data
						this.goodsSpuList.forEach(spu=>{
							spu.skus.forEach(sku=>{
								let images = JSON.parse(sku.bannerImages)
								if(images && images.length > 0){
									sku.imageUrl = images[0].materialUrl
								}
								
								// 存在一级推荐的场合
								if(sku.hasMain == BooleanEnum.TRUE && this.mainSkuList.length <= 0){
									this.mainSkuList.push(sku)
								}
								
								// 存在二级推荐的场合
								if(sku.hasSubMain == BooleanEnum.TRUE){
									this.subMainList.push(sku)
								}
							})
						})
						resolve()
					})
				})
			},
			
			/**
			 * 加载优惠券
			 */
			loadCoupon(){
				return new Promise(resolve=>{
					// 获取优惠券个数
					getAvailableCoupon().then(res=>{
						let data = res.data
						let count = data.filter(p=>p.couponCurrentStatus == couponCurrentStatusEnum.inProgress || p.couponCurrentStatus == couponCurrentStatusEnum.notStarted).length
						this.availableCouponCount = count
						resolve()
					})
				})
			},
			
			/**
			 * 切换tab
			 */
			handleTabMenuChange(e){
				this.tabCurrentIndex = e.index
			},
			
			/**
			 * 加载权益包完成
			 */
			handleEquityLoadCompleted(data){
				if(data.length > 0){
					this.tabMenuList.push({
						name:'权益包'
					})
				}
			},
			
			/**
			 * 分转元
			 */
			formatMoney(val){
				return this.formatMoneyToYuan(val)
			},
			
			/**
			 * 商品详情
			 */
			handleGoodsDetail(item){
				this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/goods/detail?spuId=${item.spuId}&skuId=${item.id}`, false)
			},

			/**
			 * 点击活动跳转
			 */
			handleNavBanner(index){
				const item = this.activityList[index]
				if(item.navType == '1'){
					this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/goods/detail?spuId=${item.spuId}&skuId=${item.skuId}`, false)
				} else if(item.navType == '2'){
					this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/equity/detail?id=${item.spuId}`, false)
				}
			},
			
			/**
			 * 点击顶部轮播图
			 */
			handleTopBanner(){
				if(!this.isLogin){
					//this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/login/index`, true, 'home')
					this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/login/index`, false)
				}
			},
			
			/**
			 * 优惠券跳转
			 */
			handleCoupon(type){
				// 优惠券
				this.jumpUtil.jumpTo(jumpTypeEnum.navigate, '/pages_one/coupon/index', true)
			},
			
			/**
			 * 跳转积分记录
			 */
			handlePoint(){
				this.jumpUtil.jumpTo(jumpTypeEnum.navigate, '/pages_one/points/record', true)
			},
			
			/**
			 * 关闭弹窗
			 */
			handleCouponClick(){
				this.isShowCoupon = false
			},
			
			/**
			 * 跳转
			 */
			handleNavUserInner(){
				if(this.userInnerIsLogin && this.userInnerInfo){
					const userNo = this.userInnerInfo.userNo
					const phone = this.userInnerInfo.phone
					// 不存在的场合，默认用户名手机号登录，兼容原来
					const type = this.userInnerInfo.type ? this.userInnerInfo.type : '1'
					const couponCode = this.userInnerInfo.couponCode
					
					// 登录
					userInnerLogin({userNo:userNo, phone:phone, type:type, couponCode:couponCode}).then(res=>{
						this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/user_inner/goods/index`, false)
					}).catch(e=>{
						// 信息错误，退出自动登录
						this.$store.dispatch("userInnerLogOut").then(res=>{
							this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/user_inner/login/index`, false)
						})
					})
				} else {
					this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/user_inner/login/index`, false)
				}
				
				// 关闭弹窗
				this.handleCouponClick()
			}
		}
	}
</script>

<style>
	/* page{
		background-color: #FFFFFF;
	} */
</style>

<style scoped>
	.hot-bg{
		background-image: linear-gradient(to right, #FFB143, #FFF3C1);
	}
	
	.text-money{
		color: #C16D09;
	}
</style>